<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="javascript,">










<meta name="description" content="这一篇让我们深入源码层面，一步一步去封装一个Promise，去了解Promise的内部实现，以便我们在项目中对Promise的使用运用自如。  实现一个简单的 Promise工具类  Promise类的结构 构造器的初始化 then方法 catch方法   添加扩展功能函数  all race resolve reject wait stop always done defer timeout s">
<meta name="keywords" content="javascript">
<meta property="og:type" content="article">
<meta property="og:title" content="深入理解 Promise (中)">
<meta property="og:url" content="http://blog.xiaowuzi.info/2016/10/05/深入理解 Promise (中)/index.html">
<meta property="og:site_name" content="小武子博客">
<meta property="og:description" content="这一篇让我们深入源码层面，一步一步去封装一个Promise，去了解Promise的内部实现，以便我们在项目中对Promise的使用运用自如。  实现一个简单的 Promise工具类  Promise类的结构 构造器的初始化 then方法 catch方法   添加扩展功能函数  all race resolve reject wait stop always done defer timeout s">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-04-14T12:37:55.105Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="深入理解 Promise (中)">
<meta name="twitter:description" content="这一篇让我们深入源码层面，一步一步去封装一个Promise，去了解Promise的内部实现，以便我们在项目中对Promise的使用运用自如。  实现一个简单的 Promise工具类  Promise类的结构 构造器的初始化 then方法 catch方法   添加扩展功能函数  all race resolve reject wait stop always done defer timeout s">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xiaowuzi.info/2016/10/05/深入理解 Promise (中)/">





  <title>深入理解 Promise (中) | 小武子博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">小武子博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xiaowuzi.info/2016/10/05/深入理解 Promise (中)/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="小武子博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">深入理解 Promise (中)</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-10-05T12:39:04+08:00">
                2016-10-05
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/javascript基础/" itemprop="url" rel="index">
                    <span itemprop="name">javascript基础</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>这一篇让我们深入源码层面，一步一步去封装一个Promise，去了解Promise的内部实现，以便我们在项目中对Promise的使用运用自如。</p>
<ul>
<li><p>实现一个简单的 Promise工具类</p>
<ul>
<li>Promise类的结构</li>
<li>构造器的初始化</li>
<li>then方法</li>
<li>catch方法</li>
</ul>
</li>
<li><p>添加扩展功能函数</p>
<ul>
<li>all</li>
<li>race</li>
<li>resolve</li>
<li>reject</li>
<li>wait</li>
<li>stop</li>
<li>always</li>
<li>done</li>
<li>defer</li>
<li>timeout</li>
<li>sequence</li>
</ul>
</li>
<li><p>测试</p>
</li>
<li>源码</li>
</ul>
<p>我在想去自己实现一个Promise类库的时候，首先会去找一些比较简洁又符合标准的一些相关实现，去分析其源码，然后结合几种实现的优点总结出自己的版本，站在巨人的肩膀上让我直接取道直径，快速的实现了我的目标，在这里非常感谢前辈们的努力和给我们留下的宝贵知识财富。</p>
<p>从标准中寻找蛛丝马迹 (以下所说的 标准 均以 <a href="https://promisesaplus.com/" target="_blank" rel="noopener">Promise/A+</a> 做为参考)，我们将依据标准，编写一个可通过标准测试的Promise类库。</p>
<a id="more"></a>
<h2 id="Promise类的结构"><a href="#Promise类的结构" class="headerlink" title="Promise类的结构"></a>Promise类的结构</h2><p>标准中规定：</p>
<ol>
<li>Promise对象初始状态为 Pending，在被 resolve 或 reject 时，状态变为 Fulfilled 或 Rejected</li>
<li>resolve接收成功的数据，reject接收失败或错误的数据</li>
<li>Promise对象必须有一个 then 方法，且只接受两个可函数参数 onFulfilled、onRejected</li>
</ol>
<p>由以上标准就容易就能实现这个类的大致结构</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">function Promise(resolver)&#123;</span><br><span class="line">	if(resolver &amp;&amp; typeof resolver!==&apos;function&apos;)&#123;</span><br><span class="line">		throw new Error(&apos;Promise resolver is not a function&apos;);</span><br><span class="line">	&#125;</span><br><span class="line">	//当前promise对象的状态</span><br><span class="line">	this.state=PENDING;</span><br><span class="line">	//当前promise对象的数组(成功或失败)</span><br><span class="line">	this.data=UNDEFINED;</span><br><span class="line">	//当前promise对象注册的回调队列</span><br><span class="line">	this.callbackQueue=[];</span><br><span class="line">	//执行resolve()或reject()方法</span><br><span class="line">	if(resolver) executeResolve.call(this,resolver);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Promise.prototye.then=function()&#123;&#125;</span><br></pre></td></tr></table></figure>
<p>所以，一个 Promise构造函数 和一个实例方法then 就是Promise的核心的了，其它的都是Promise的语法糖或者说是扩展。</p>
<h3 id="构造器的初始化"><a href="#构造器的初始化" class="headerlink" title="构造器的初始化"></a>构造器的初始化</h3><p>使用 new Promise(function(resolve, reject){…} )实例化 Promise 时，去改变promise的状态，是执行 resolve() 或 reject()方法，那么，resolver的两个参数分别是成功的操作函数和失败的操作函数。</p>
<h4 id="executeResolver"><a href="#executeResolver" class="headerlink" title="executeResolver"></a>executeResolver</h4><p>这里将上面执行 resolver 的方法抽象出来，内部再将 resovle 和 reject 两个参数包装成 成功和失败的回调。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">function executeResolver()&#123;</span><br><span class="line">	var called=false,_this=this;</span><br><span class="line">	function onError(value)&#123;</span><br><span class="line">		if(called)&#123;return;&#125;</span><br><span class="line">		called=true;</span><br><span class="line">		executeCallback.bind(_this)(&apos;reject&apos;,value);</span><br><span class="line">	&#125;</span><br><span class="line">	function onSuccess(value)&#123;</span><br><span class="line">		if(called)&#123; return;&#125;</span><br><span class="line">		called=true;</span><br><span class="line">		executeCallback.bind(_this)(&apos;resolve&apos;,value);</span><br><span class="line">	&#125;</span><br><span class="line">	try&#123;</span><br><span class="line">		resolver(onSuccess,onError);</span><br><span class="line">	&#125;catch(e)&#123;</span><br><span class="line">		onError(e);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="executeCallback"><a href="#executeCallback" class="headerlink" title="executeCallback"></a>executeCallback</h4><p>因为执行 resolved() 或 reject() 内部主要作用是更改当前实例的状态为 rejected 或 resolved，然后执行当前实例 then() 中注册的 成功或失败的回调函数， 所以从过程上来看，大致是相同的，抽象出来共用</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">function executeCallback(type,x)&#123;</span><br><span class="line">	var isResolve=type===&apos;resolve&apos;,thenable;</span><br><span class="line">	</span><br><span class="line">	if(isResolve &amp;&amp; (typeof x===&apos;object&apos; || typeof x===&apos;function&apos;))&#123;</span><br><span class="line">		try&#123;</span><br><span class="line">			thenable=getTen(x);</span><br><span class="line">		&#125;catch(e)&#123;</span><br><span class="line">			return executeCallback.bind(this)(&apos;reject&apos;,e);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	if(isResolve &amp;&amp; thenable)&#123;</span><br><span class="line">		executeResolver.bind(this)(thenable);</span><br><span class="line">	&#125;else&#123;</span><br><span class="line">		this.state=isResolve? RESOLVED:REJECTED;</span><br><span class="line">		this.data=x;</span><br><span class="line">		this.callbackQueue &amp;&amp; this.callbackQueue.length &amp;&amp; this.callbackQueue.forEach(v =&gt; v[type](x));</span><br><span class="line">    &#125;</span><br><span class="line">	return this;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="getThen"><a href="#getThen" class="headerlink" title="getThen"></a>getThen</h4><p>用于判断是否是thenable对象，如果是，则返回一个执行thenabled中then方法的函数</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">function getThen(obj)&#123;</span><br><span class="line">	var then=obj &amp;&amp; obj.then;</span><br><span class="line">	if(obj &amp;&amp; typeof obj===&apos;object&apos; &amp;&amp; typeof then===&apos;function&apos;)&#123;</span><br><span class="line">		return function appyThen()&#123;</span><br><span class="line">			then.apply(obj,arguments);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>到这里，Promise实例初始化的处理逻辑就完成了</p>
<p>执行下面这段代码将不会有任何输出，但是promise的状态发生了改变，也就是this.status为resolved，this.data为ok</p>
<p><code>new Promise(resolve=&gt;resolve(&#39;ok&#39;))</code></p>
<p>至于如何在resolve()调用之后，去执行then方法注册的onResolved回调，下面继续分析</p>
<h4 id="then方法"><a href="#then方法" class="headerlink" title="then方法"></a>then方法</h4><p>标准中规定：</p>
<ol>
<li>then 方法必须返回一个新的 Promise实例（ES6中的标准，Promise/A+中没有明确说明）</li>
<li>为了保证 then中回调的执行顺序，onFulfilled 或 onRejected 必须异步调用</li>
</ol>
<p>对应标准看具体实现</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">Promise.prototype.then=function(onResolved,onRejected)&#123;</span><br><span class="line">	if(typeof onResolved!==&apos;function&apos; &amp;&amp; this.state===RESOLVED || typeof onRejected!==&apos;function&apos; || this.state===REJECTED&#123;</span><br><span class="line">		return this;</span><br><span class="line">	&#125;</span><br><span class="line">	//实例化一个新的Promise对象</span><br><span class="line">	var promise=new this.constructor();</span><br><span class="line">	</span><br><span class="line">	//一般情况下，状态发生改变时，走这里</span><br><span class="line">	if(this.state!==PENDING)&#123;</span><br><span class="line">		var callback=this.state==RESOLVED? onResolved:onRejected;</span><br><span class="line">		executeCallbackAsync.bind(promise)(callback,this.data);</span><br><span class="line">	&#125;else&#123;</span><br><span class="line">		this.callbackQueue.forEach(v=&gt;v[type](x));</span><br><span class="line">	&#125;</span><br><span class="line">	return promise;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="executeCallbackAsync"><a href="#executeCallbackAsync" class="headerlink" title="executeCallbackAsync"></a>executeCallbackAsync</h4><p>上面将异步调用callback的逻辑抽象成一个方法executeCallbackAsync，这个方法主要功能是安全的执行callback方法</p>
<p>如果出错，则自动调用reject(reason)方法并理性状态为rejected，传递错误数据给当前实例then方法中注册的onRejected回调<br>如果成功，则自动调用resolve(value)方法并更改为resolved，传递数据给当前实例then方法中注册的onResolved回调</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">function executeCallbackAsync(callback,value)&#123;</span><br><span class="line">	var _this=this;</span><br><span class="line">	setTimeout(function()&#123;</span><br><span class="line">		var res;</span><br><span class="line">		try&#123;</span><br><span class="line">			res=callback(value);</span><br><span class="line">		&#125;catch(e)&#123;</span><br><span class="line">			return executeCallback.bind(_this)(&apos;reject&apos;,e);</span><br><span class="line">		&#125;</span><br><span class="line">		if(res!==_this)&#123;</span><br><span class="line">			return executeCallback.bind(_this)(res);</span><br><span class="line">		&#125;else&#123;</span><br><span class="line">			return excuteCallback.bind(_this)(&apos;reject&apos;,new TypeError(&apos;Cannot resolve promise with itself&apos;));</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;,1);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="注意"><a href="#注意" class="headerlink" title="注意"></a>注意</h4><p>这里最好不要用setTimeout,使用setTimeout可以异步执行回调，但其实并不是真正的异步线程，而是利用了浏览器Event Loop机制去触发执行回调，而浏览器的事件轮循时间间隔是4ms，而在nodejs中的Event Loop时间间隔是1ms,所以会产生一定的延迟，如果promise链比较长，延迟就会越明显，这里可以引入NPM上的immediate模块来异步无延迟的执行回调。</p>
<h4 id="CallbackItem"><a href="#CallbackItem" class="headerlink" title="CallbackItem"></a>CallbackItem</h4><p>上面then中对于回调的处理，使用了一个回调对象来管理注册的回调，将回调按顺序添加至callbackQueue队列中，调用时，依次调用。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">function CallbackItem(promise,onResolved,onRejected)&#123;</span><br><span class="line">	this.promise=promise;</span><br><span class="line">	this.onResolved=typeof</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">CallbackItem.prototype.resolve=function(value)&#123;</span><br><span class="line">	executeCallbackAsync.bind(this.promise)(this.onResolved,value);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">CallbackItem.prototype.reject=function(value)&#123;</span><br><span class="line">	executeCallbackAsync.bind(this.promise)(this.onRejected,value);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="catch方法"><a href="#catch方法" class="headerlink" title="catch方法"></a>catch方法</h4><p>由于catch方法是then(null,onRejected)的语法糖，所以这里也很好实现</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Promise.prototype.catch=function(onRejected)&#123;</span><br><span class="line">	return this.then(null,onRejected);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>到这里，我们自定义的Promise的相关代码核心都实现完成了，下面可以测试一下</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">function fn1()&#123;</span><br><span class="line">	var promise=new Promise(resolve=&gt;resolve(1))</span><br><span class="line">	promise.then(res=&gt;console.log(++res));</span><br><span class="line">	promise.then(res=&gt;console.log(++res))</span><br><span class="line">	promise.then(res=&gt;console.log(++res))</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">fn1();</span><br><span class="line">//2,2,2</span><br><span class="line">function fn2()&#123;</span><br><span class="line">	var promise=new Promise((resolve,reject)=&gt;&#123;</span><br><span class="line">		resolve(1);</span><br><span class="line">	&#125;)</span><br><span class="line">	.then(res=&gt;(res++,console.log(res),res))</span><br><span class="line">	.then(res=&gt;(res++,console.log(res),res))</span><br><span class="line">	.then(res=&gt;(res++,console.log(res),res));</span><br><span class="line">&#125;</span><br><span class="line">fn2();</span><br><span class="line"></span><br><span class="line">function fn3()&#123;</span><br><span class="line">	return new Promise((resolve,reject)=&gt;reject(999));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">fn3().catch(err=&gt;console.log(err));</span><br></pre></td></tr></table></figure>
<h3 id="添加扩展方法"><a href="#添加扩展方法" class="headerlink" title="添加扩展方法"></a>添加扩展方法</h3><p>Promise的扩展方法都是基于Promise的构造函数和then方法的实现，不同的类库实现方式不同，部分API意义也不同</p>
<h4 id="all"><a href="#all" class="headerlink" title="all"></a>all</h4><p>用于并行执行promise组成的数组(数组中可以不是Promise对象，在调用过程中会使用Promise.resolve(value)转换成Promise对象)，如果全部成功则获得成功的结果组成的数组对象，如果失败，则获得失败的信息，返回一个新的Promise对象</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">Promise.all=function(iterable)&#123;</span><br><span class="line">	var _this=this;</span><br><span class="line">	return new this(function(resolve,reject)&#123;</span><br><span class="line">		if(!iterable || !Array.isArray(iterable)) return reject( new TypeError(&apos;must be an array&apos;) );</span><br><span class="line">		var len=iterable.length;</span><br><span class="line">		if(!len) return resolve([]);</span><br><span class="line">		var res=Array(len),called=false;</span><br><span class="line">		iterable.forEach(function(v,i)&#123;</span><br><span class="line">			(function(i)&#123;</span><br><span class="line">				_this.resolve(v).then(function()&#123;</span><br><span class="line">					res[i]=value;</span><br><span class="line">					if(++counter===len &amp;&amp; !called)&#123;</span><br><span class="line">						called=true;</span><br><span class="line">						return resolve(res);</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;,function(err)&#123;</span><br><span class="line">					if(!called)&#123;</span><br><span class="line">						called=true;</span><br><span class="line">						return reject(err);</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;);</span><br><span class="line">			&#125;)(i);</span><br><span class="line">		&#125;);</span><br><span class="line">	&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>使用方式</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">function fn1()&#123;</span><br><span class="line">	return new Promise(resolve=&gt;setTimeout(()=&gt;resolve(1),3000));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function fn2()&#123;</span><br><span class="line">	return new Promise(resolve=&gt;setTimeout(()=&gt;resolve(2),2000));</span><br><span class="line">&#125;</span><br><span class="line">Promise.all([fn1(),fn2()]).then(res=&gt;);</span><br></pre></td></tr></table></figure>
<p>这里的实现，要注意一点的是，即要保证全部成功，又要保证按数组里原来的顺序返回结果，在一开始的实现里，我并没有考虑到这个问题，所以最初的实现是没有添加闭包的，那么结果就是数组里的promise谁先成功，谁的结果就占据了第一个位置，就算这个promise是数组的最后一个</p>
<h4 id="race"><a href="#race" class="headerlink" title="race"></a>race</h4><p>用于并行执行promise组成的数组（数组中可以不是Promise对象，在调用过程中会使用Promise.resolve(value)转换成Promise对象），如果某个Promise的状态率先改变，就获得改变的结果，返回一个新的Promise对象</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">Promise.race=function(iterable)&#123;</span><br><span class="line">	var _this=this;</span><br><span class="line">	return new this(function(resolve,reject)&#123;</span><br><span class="line">		if(!iterable || !Array.isArray(iterable)) return reject( new TypeError(&apos;must be an array&apos;) );</span><br><span class="line">		var len=iterable.length;</span><br><span class="line">		if(!len) return resolve([]);</span><br><span class="line">		</span><br><span class="line">		var called=false;</span><br><span class="line">		iterable.forEach(function(v,i)&#123;</span><br><span class="line">			_this.resolve(v).then(function(res)&#123;</span><br><span class="line">				if(!called)&#123;</span><br><span class="line">					called=true;</span><br><span class="line">					return resolve(res);</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;,function(err)&#123;</span><br><span class="line">			if(!called)&#123;</span><br><span class="line">				called=true;</span><br><span class="line">				return reject(err);</span><br><span class="line">			&#125;</span><br><span class="line">			&#125;);</span><br><span class="line">		&#125;);</span><br><span class="line">	&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>因为race是返回单个的结果，所以不存类似于all的情况</p>
<p>使用方式</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">function fn1()&#123;</span><br><span class="line">	return new Promise(resolve=&gt;setTime(()=&gt;resolve(1),3000));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">function fn2()&#123;</span><br><span class="line">	return new Promise(resolve=&gt;setTimeout(()=&gt;resolve(2),2000));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Promise.race([fn1(),fn2()]).then(res=&gt;console.log(res),err=&gt;console.log(err));</span><br></pre></td></tr></table></figure>
<h4 id="resolve"><a href="#resolve" class="headerlink" title="resolve"></a>resolve</h4><p>用于包装任意对象为promise对象，返回一个新的promise,并且状态是resolved</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Promise.resolve=function(value)&#123;</span><br><span class="line">	if(value instanceof this) return value;</span><br><span class="line">	return executeCallback.bind(new this())(&apos;resolve&apos;,value);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="reject"><a href="#reject" class="headerlink" title="reject"></a>reject</h4><p>用于包装任意对象为promise对象，返回一个新的promise,并且状态是rejected</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Promise.reject=function(value)&#123;</span><br><span class="line">	if(value instanceof this) return value;</span><br><span class="line">	return executeCallback.bind(new this())(&apos;reject&apos;,value);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="wait"><a href="#wait" class="headerlink" title="wait"></a>wait</h4><p>用于一个promise任务结束后等待指定的时间再去执行一些操作</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">Promise.prototype.wait=function(ms)&#123;</span><br><span class="line">	var P=this.constructor;</span><br><span class="line">	reutrn this.then(function(v)&#123;</span><br><span class="line">		return new P(function(resovle,reject)&#123;</span><br><span class="line">			setTimeout(function()&#123;</span><br><span class="line">				resolve(v);</span><br><span class="line">			&#125;,~~ms);</span><br><span class="line">		&#125;);</span><br><span class="line">	&#125;,function(r)&#123;</span><br><span class="line">		return new P(function(resolve,reject)&#123;</span><br><span class="line">			setTimout(function()&#123;</span><br><span class="line">				reject(r);</span><br><span class="line">			&#125;,~~ms);</span><br><span class="line">		&#125;);</span><br><span class="line">	&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>使用<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">fn1().wait(2000).then(res=&gt;console.log(res),err=&gt;console.log(err));</span><br></pre></td></tr></table></figure></p>
<p>这里考虑到，wait是用于promise实例对象上的，那么为了可以保证链式调用，必须返回一个新的promise，并且上一步的成功和失败的消息不能丢失，继续向后传递，这里只做延迟处理。</p>
<h4 id="stop"><a href="#stop" class="headerlink" title="stop"></a>stop</h4><p>用于中断promise链</p>
<p>通常在promise链中去reject或throw,或者是异常报错信息，promise内部都会使用try…catch转换为reject方法往后传递，无法中断后面的then或其它方法的执行，那么这里利用,then方法中对状态的要求必须不是pending状态的处理才会立即执行回调，在promise链中返回一个初始状态的promise对象，便可以中断后面回调的执行。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Promise.stop=function()&#123;</span><br><span class="line">	return new this();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>使用</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Promise.resolve(1).then(res=&gt;&#123;</span><br><span class="line">	console.log(&apos;发生错误，停止后面的执行&apos;);</span><br><span class="line">	return Promise.stop();</span><br><span class="line">&#125;).then(res=&gt;console.log(res)).catch(err=&gt;console.log(err));</span><br></pre></td></tr></table></figure>
<h4 id="always"><a href="#always" class="headerlink" title="always"></a>always</h4><p>无论成功还是失败最终都会调用always中注册回调<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Promise.prototype.always=function(fn)&#123;</span><br><span class="line">	return this.then(function(v)&#123;</span><br><span class="line">		reutrn fn(v),v;</span><br><span class="line">	&#125;,function(r)&#123;</span><br><span class="line">		throw fn(r), r;</span><br><span class="line">	&#125;);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure></p>
<p>使用<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ajaxLoadData().then(res=&gt;console.log(res),err=&gt;console.log(err)).always(()=&gt;console.log(&apos;关闭loading动画&apos;));</span><br></pre></td></tr></table></figure></p>
<h4 id="done"><a href="#done" class="headerlink" title="done"></a>done</h4><p>由于promise在执行 resolve 或 onResolved 回调时，使用了try…catch，并将错误信息，使用 reject方法 传递了出去，但是如果后面没有注册处理reject的回调函数，那么错误信息将无法得到处理，进而消失不见，难以查觉，所以有了 done 方法。</p>
<p>done方法并不返回promise对象，也就是done之后不能使用 then或catch了，其主要作用就是用于将 promise链 中未捕获的异常信息抛至外层，并不会对错误信息进行处理。</p>
<p>done方法必须应用于promise链的最后</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Promise.prototype.done=function(onResolved,onRejected)&#123;</span><br><span class="line">	this.then(onResolved,onRejected).catch(function(error)&#123;</span><br><span class="line">		setTimeout(function()&#123;</span><br><span class="line">			throw error;</span><br><span class="line">		&#125;,0);</span><br><span class="line">	&#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>使用</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">ajaxLoadData()</span><br><span class="line">.then(res=&gt;&#123;</span><br><span class="line">	return new Promise((resolve,reject)=&gt;reject(&apos;未捕获的错误&apos;));</span><br><span class="line">&#125;,err=&gt;console.log(err)).always(()=&gt;console.log(&apos;关闭loading动画&apos;)).done();</span><br></pre></td></tr></table></figure>
<h4 id="defer"><a href="#defer" class="headerlink" title="defer"></a>defer</h4><p>Deferred 的简称，叫延迟对象，其实是 new Promise() 的语法糖</p>
<p>与Promise的关系</p>
<ul>
<li>Deferred 拥有 Promise</li>
<li>Deferred 具备对 Promise的状态进行操作的特权方法</li>
<li>Promise 代表了一个对象，这个对象的状态会在未来改变</li>
<li>Deferred对象 表示了一个处理没有结束，在状态发生改变时，再使用Promise来处理结果</li>
</ul>
<p>优缺点</p>
<ul>
<li>不用使用大括号将逻辑包起来，少了一层嵌套</li>
<li>但是缺少了Promise的错误处理逻辑<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Promise.deferred=Promise.defer=function()&#123;</span><br><span class="line">	var dfd=&#123;&#125;;</span><br><span class="line">	dfd.promise=new this(function(resolve,reject)&#123;</span><br><span class="line">		dfd.resolve=resolve;</span><br><span class="line">		dfd.reject=reject;</span><br><span class="line">	&#125;);</span><br><span class="line">	return dfd;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>使用<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">function getURL(URL)&#123;</span><br><span class="line">	var deferred=Promise.deferred;</span><br><span class="line">	var req = new XMLHttpRequest();</span><br><span class="line">    req.open(&apos;GET&apos;, URL, true);</span><br><span class="line">    req.onload = function () &#123;</span><br><span class="line">        if (req.status === 200) &#123;</span><br><span class="line">            deferred.resolve(req.responseText);</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            deferred.reject(new Error(req.statusText));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">    req.onerror = function () &#123;</span><br><span class="line">        deferred.reject(new Error(req.statusText));</span><br><span class="line">    &#125;;</span><br><span class="line">    req.send();</span><br><span class="line">    return deferred.promise;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="timeout"><a href="#timeout" class="headerlink" title="timeout"></a>timeout</h4><p>用于判断某些promise任务是否超时,如一个异步请求，如果超时，取消息请求，提示消息或重新请求</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Promise.timeout=function(promise,ms)&#123;</span><br><span class="line">	return this.race([promise,this.reject().wait(ms)]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>用法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">function fn4()&#123;</span><br><span class="line">	return new Promise(resolve=&gt;setTimeout(()=&gt;resolve(1),3000))</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Promise.timeout(fn4(),2000).then(res=&gt;console.log(res),err=&gt;console.log(err));</span><br></pre></td></tr></table></figure></p>
<p>参考地址：<br><a href="http://coderlt.coding.me/2016/12/04/promise-in-depth-an-introduction-2/" target="_blank" rel="noopener">深入理解 Promise (中)</a></p>
      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center">
  <div>Donate comment here</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="Tony 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Tony 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/javascript/" rel="tag"># javascript</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/10/04/深入理解Promise/" rel="next" title="深入理解Promise">
                <i class="fa fa-chevron-left"></i> 深入理解Promise
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/10/06/深入理解 Promise (上)/" rel="prev" title="深入理解 Promise (上)">
                深入理解 Promise (上) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Tony</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">65</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Promise类的结构"><span class="nav-number">1.</span> <span class="nav-text">Promise类的结构</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#构造器的初始化"><span class="nav-number">1.1.</span> <span class="nav-text">构造器的初始化</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#executeResolver"><span class="nav-number">1.1.1.</span> <span class="nav-text">executeResolver</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#executeCallback"><span class="nav-number">1.1.2.</span> <span class="nav-text">executeCallback</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#getThen"><span class="nav-number">1.1.3.</span> <span class="nav-text">getThen</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#then方法"><span class="nav-number">1.1.4.</span> <span class="nav-text">then方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#executeCallbackAsync"><span class="nav-number">1.1.5.</span> <span class="nav-text">executeCallbackAsync</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#注意"><span class="nav-number">1.1.6.</span> <span class="nav-text">注意</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#CallbackItem"><span class="nav-number">1.1.7.</span> <span class="nav-text">CallbackItem</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#catch方法"><span class="nav-number">1.1.8.</span> <span class="nav-text">catch方法</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#添加扩展方法"><span class="nav-number">1.2.</span> <span class="nav-text">添加扩展方法</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#all"><span class="nav-number">1.2.1.</span> <span class="nav-text">all</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#race"><span class="nav-number">1.2.2.</span> <span class="nav-text">race</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#resolve"><span class="nav-number">1.2.3.</span> <span class="nav-text">resolve</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#reject"><span class="nav-number">1.2.4.</span> <span class="nav-text">reject</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#wait"><span class="nav-number">1.2.5.</span> <span class="nav-text">wait</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#stop"><span class="nav-number">1.2.6.</span> <span class="nav-text">stop</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#always"><span class="nav-number">1.2.7.</span> <span class="nav-text">always</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#done"><span class="nav-number">1.2.8.</span> <span class="nav-text">done</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#defer"><span class="nav-number">1.2.9.</span> <span class="nav-text">defer</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#timeout"><span class="nav-number">1.2.10.</span> <span class="nav-text">timeout</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  



  
  









  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>